package com.example.pan.ui.drive

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import com.example.pan.databinding.ItemDriveBinding
import com.example.pan.model.BAIDU_DRIVE
import com.example.pan.model.Drive
import com.example.pan.ui.base.BaseViewHolder

class DriveAdapter : PagingDataAdapter<Drive, BaseViewHolder<ItemDriveBinding>>(Callback()) {

    private var listener: OnClickListener? = null

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BaseViewHolder<ItemDriveBinding> {
        val binding = ItemDriveBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return BaseViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BaseViewHolder<ItemDriveBinding>, position: Int) {
        getItem(position)?.let { drive ->
            holder.binding.apply {
                title.text = resolveTitle(drive.type, drive.title)
                root.setOnClickListener {
                    listener?.onItemClick(drive)
                }
            }
        }
    }

    private fun resolveTitle(type: Int, title: String): String {
        return when (type) {
            BAIDU_DRIVE -> "${title}的百度网盘"
            else -> ""
        }
    }

    fun setOnClickListener(listener: OnClickListener) {
        this.listener = listener
    }

    interface OnClickListener {

        fun onItemClick(drive: Drive)

    }


    internal class Callback : DiffUtil.ItemCallback<Drive>() {
        override fun areItemsTheSame(oldItem: Drive, newItem: Drive): Boolean {
            return oldItem.token == newItem.token
        }

        override fun areContentsTheSame(oldItem: Drive, newItem: Drive): Boolean {
            return oldItem == newItem
        }

    }
}